package com.mic.yzzn.plc.common.instructions.request;


import com.mic.yzzn.plc.common.ins.datastructure.PLCContactorNumber;
import com.mic.yzzn.plc.common.instructions.basic.PLCRequestInstruction;

/**
 * Created by ASH on 16/3/7.
 */
public class PLCSingleContactorInstruction extends PLCRequestInstruction
{
    /** 触点代码 */
    protected String contactorCode;
    /** 触点编号 BCD(3) + HEX(1) */
    protected PLCContactorNumber contactorNumber;

    /**
     * 初始化方法
     */
    public PLCSingleContactorInstruction()
    {
        contactorNumber = new PLCContactorNumber();
    }

    /**
     * 转化成字符串
     */
    @Override
    public String toString()
    {
        // 拼接指令字符串
        StringBuffer buffer = new StringBuffer();
        buffer.append(instructionHeader);
        buffer.append(locationNumber_high);
        buffer.append(locationNumber_low);
        buffer.append(instructionTypeCode);
        buffer.append(requestCode);
        buffer.append(contactorCode);
        buffer.append(contactorNumber.toString());
        buffer.append(getBBC_high());
        buffer.append(getBBC_low());
        buffer.append(instructionEnd);

        return buffer.toString();
    }

    /**
     * 触点代码get方法
     * @return 触点代码
     */
    public String getContactorCode()
    {
        return contactorCode;
    }

    /**
     * 触点编号get方法
     * @return 触点编号
     */
    public PLCContactorNumber getContactorNumber()
    {
        return contactorNumber;
    }

    /**
     * 触点代码set方法
     * @param contactorCode
     */
    public void setContactorCode(String contactorCode)
    {
        this.contactorCode = contactorCode;
    }

    /**
     * 触点编号set方法
     * @param contactorNumber
     */
    public void setContactorNumber(PLCContactorNumber contactorNumber)
    {
        this.contactorNumber = contactorNumber;
    }

    /**
     * 计算并且返回自己的每一位异或值
     */
    @Override
    protected int getXORByBit()
    {
        int i = 0;
        int result = 0;

        for (i = 0; i < contactorCode.length(); ++i)
        {
            result ^= contactorCode.charAt(i);
        }

        return super.getXORByBit() ^ contactorNumber.getXORByBit() ^ result;
    }

}
